﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GeneralForum : System.Web.UI.Page
{
    private static List<ForumEntry> forum;

    protected void Page_Load(object sender, EventArgs e)
    {


        if (IsPostBack)
        {

        }
        else
        {
            SetupForum();
        }
    }


    private void SetupForum()
    {
        ForumDatabaseAdapter adapter = new ForumDatabaseAdapter();
        adapter.Open();

        if (!adapter.DoesTableExist(ForumDatabaseAdapter.FORUM_ENTRY_TABLE))
        {
            adapter.CreateTable(ForumDatabaseAdapter.FORUM_ENTRY_TABLE,
                    ForumDatabaseAdapter.FORUM_COLUMNS);
        }

        if (Session["ForumName"] != null)
        {
            ForumList forums = ForumList.GetForumListObject();
            Forum f = forums.RetrieveForumObject((string)Session["ForumName"]);
            forum = adapter.GetAllPosts(f.TableName);
            lblForumHeader.InnerText = f.ForumName;
            lblRules.Text = f.Description;
        }
        else
            forum = adapter.GetAllPosts();

        ForumEntryArea.InnerHtml = GetContent();
        adapter.Close();
    }

    protected void btnPostComment_Click(object sender, EventArgs e)
    {
        PostComment();
    }

    private void PostComment()
    {
        ForumEntryArea.InnerHtml = "";
        AddEntryToForumList();
        ForumEntryArea.InnerHtml = GetContent();
    }

    private static string GetContent()
    {
        string content = "<hr /> ";
        foreach (ForumEntry forumEntry in forum)
            content += string.Format("<p> <h2>{0}</h2> </p> <p>{1}</p> <p> <b>{2}</b> </p> <hr /> <br />",
                                    forumEntry.Subject, forumEntry.Comment, forumEntry.Signature);
        return content;
    }

    private void AddEntryToForumList()
    {
        ForumEntry entry = new ForumEntry();
        ForumDatabaseAdapter adapter = new ForumDatabaseAdapter();

        entry.Subject = txtSubject.Text;
        entry.Comment = txtComment.Text;
        entry.Signature = txtSignature.Text;
        //forum.Add(entry);

        string currentdir = System.IO.Directory.GetCurrentDirectory();
        adapter.Open();
        if (Session["ForumName"] != null)
        {
            ForumList forums = ForumList.GetForumListObject();
            Forum f = forums.RetrieveForumObject((string)Session["ForumName"]);
            adapter.AddPost(entry.Subject, entry.Comment, entry.Signature, f.TableName);
            forum = adapter.GetAllPosts(f.TableName);
        }
        else
        {
            adapter.AddPost(entry.Subject, entry.Comment, entry.Signature);
            forum = adapter.GetAllPosts();
        }
        adapter.Close();
    }

}